import React, { useEffect, useRef, useState } from 'react';

// 声明全局 libpag 类型
declare global {
  interface Window {
    libpag: any;
  }
}

interface PAGPlayerProps {
  src: string;
  autoPlay?: boolean;
  loop?: boolean;
  playbackRate?: number;
  width?: number | string;
  height?: number | string;
  style?: React.CSSProperties;
  onPlay?: () => void;
  onEnd?: () => void;
  onError?: (error: Error) => void;
}

const PAGPlayer: React.FC<PAGPlayerProps> = ({
  src,
  autoPlay,
  loop = false,
  playbackRate = 1,
  width = '100%',
  height = '100%',
  style,
  onPlay,
  onEnd,
  onError,
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const pagViewRef = useRef<any>(null);
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    if (!canvasRef.current) return;

    const loadPAG = async () => {
      try {
        if (!window.libpag) {
            await new Promise((resolve) => {
              const check = () => {
                if (window.libpag) resolve(true);
                else setTimeout(check, 100);
              };
              check();
            });
          }
          
          const PAG = await window.libpag.PAGInit();
          const buffer = await fetch(src).then((response) => response.arrayBuffer());
          const pagFile = await PAG.PAGFile.load(buffer);
          const pagView:any = await PAG.PAGView.init(pagFile, canvasRef.current!);
         
         pagViewRef.current = pagView;
         if (pagView.setProgress && playbackRate !== 1) {
            const updateProgress = () => {
              const currentTime = pagView.getProgress() * pagView.duration();
              const newTime = currentTime + (16 * playbackRate); // 16ms per frame
              pagView.setProgress(newTime / pagView.duration());
              if (pagView.isPlaying()) {
                requestAnimationFrame(updateProgress);
              }
            };
            pagView.addListener('onAnimationPlay', updateProgress);
          }
 
         pagView.addListener('onAnimationStart', () => {
           onPlay?.();
         });
 
         pagView.addListener('onAnimationEnd', () => {
           onEnd?.();
         });
 
         setIsLoaded(true);
 
         if (autoPlay) {
           pagView.play();
         }
      } catch (error) {
        console.error('PAG初始化失败:', error);
        onError?.(error as Error);
      }
    };

    loadPAG();

    return () => {
      if (pagViewRef.current) {
        pagViewRef.current.destroy();
        pagViewRef.current = null;
      }
    };
  }, [src]);

  useEffect(() => {
    if (pagViewRef.current) {
      pagViewRef.current.setPlaybackRate(playbackRate);
    }
  }, [playbackRate]);

  useEffect(() => {
    if (pagViewRef.current) {
      pagViewRef.current.setRepeatCount(loop ? 0 : 1);
    }
  }, [loop]);

  return (
    <div style={{ width, height, position: 'relative', overflow: 'hidden', ...style }}>
      <canvas
        ref={canvasRef}
        style={{ width: '100%', height: '100%', display:'block' }}
      />

    </div>
  );
};

export default PAGPlayer;